package org.example.backend.service.impl;

import lombok.RequiredArgsConstructor;
import org.example.backend.dto.TicketDTO;
import org.example.backend.dto.TicketOrderDTO;
import org.example.backend.entity.Ticket;
import org.example.backend.entity.TicketOrder;
import org.example.backend.entity.User;
import org.example.backend.exception.BusinessException;
import org.example.backend.repository.TicketOrderRepository;
import org.example.backend.repository.TicketRepository;
import org.example.backend.service.TicketService;
import org.example.backend.service.UserService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;

@Service
@RequiredArgsConstructor
public class TicketServiceImpl implements TicketService {

    private final TicketRepository ticketRepository;
    private final TicketOrderRepository orderRepository;
    private final UserService userService;

    @Override
    @Transactional
    public Ticket createTicket(TicketDTO ticketDTO) {
        Ticket ticket = new Ticket();
        ticket.setName(ticketDTO.getName());
        ticket.setPrice(ticketDTO.getPrice());
        ticket.setDescription(ticketDTO.getDescription());
        ticket.setIsActive(ticketDTO.getIsActive() != null ? ticketDTO.getIsActive() : true);
        
        return ticketRepository.save(ticket);
    }

    @Override
    @Transactional
    public Ticket updateTicket(Long id, TicketDTO ticketDTO) {
        Ticket ticket = ticketRepository.findById(id)
                .orElseThrow(() -> new BusinessException("门票不存在"));
        
        ticket.setName(ticketDTO.getName());
        ticket.setPrice(ticketDTO.getPrice());
        ticket.setDescription(ticketDTO.getDescription());
        ticket.setIsActive(ticketDTO.getIsActive());
        
        return ticketRepository.save(ticket);
    }

    @Override
    @Transactional
    public void deleteTicket(Long id) {
        Ticket ticket = ticketRepository.findById(id)
                .orElseThrow(() -> new BusinessException("门票不存在"));
                
        if (orderRepository.existsByTicketAndVisitDateGreaterThanEqual(ticket, LocalDate.now())) {
            throw new BusinessException("该门票已有未使用的订单，无法删除");
        }
        
        ticketRepository.deleteById(id);
    }

    @Override
    public Ticket getTicket(Long id) {
        return ticketRepository.findById(id)
                .orElseThrow(() -> new BusinessException("门票不存在"));
    }

    @Override
    public Page<Ticket> getTickets(Boolean isActive, Pageable pageable) {
        if (isActive != null) {
            return ticketRepository.findByIsActive(isActive, pageable);
        }
        return ticketRepository.findAll(pageable);
    }

    @Override
    @Transactional
    public TicketOrder createOrder(TicketOrderDTO orderDTO) {
        Ticket ticket = ticketRepository.findById(orderDTO.getTicketId())
                .orElseThrow(() -> new BusinessException("门票不存在"));
                
        if (!ticket.getIsActive()) {
            throw new BusinessException("该门票已停售");
        }
        
        if (orderDTO.getVisitDate().isBefore(LocalDate.now())) {
            throw new BusinessException("游玩日期不能早于今天");
        }

        User user = userService.getCurrentUser();
        
        TicketOrder order = new TicketOrder();
        order.setTicket(ticket);
        order.setUser(user);
        order.setQuantity(orderDTO.getQuantity());
        order.setVisitDate(orderDTO.getVisitDate());
        order.setTotalAmount(ticket.getPrice().multiply(BigDecimal.valueOf(orderDTO.getQuantity())));
        order.setOrderTime(LocalDateTime.now());
        order.setStatus("CREATED");
        
        return orderRepository.save(order);
    }

    @Override
    public TicketOrder getOrder(Long id) {
        User user = userService.getCurrentUser();
        return orderRepository.findByIdAndUser(id, user)
                .orElseThrow(() -> new BusinessException("订单不存在"));
    }

    @Override
    public Page<TicketOrder> getUserOrders(Pageable pageable) {
        User user = userService.getCurrentUser();
        return orderRepository.findByUser(user, pageable);
    }

    @Override
    public Page<TicketOrder> getAllOrders(LocalDate startDate, LocalDate endDate, Pageable pageable) {
        if (startDate != null && endDate != null) {
            return orderRepository.findByVisitDateBetween(startDate, endDate, pageable);
        }
        return orderRepository.findAll(pageable);
    }

    @Override
    @Transactional
    public void cancelOrder(Long id) {
        User user = userService.getCurrentUser();
        TicketOrder order = orderRepository.findByIdAndUser(id, user)
                .orElseThrow(() -> new BusinessException("订单不存在"));
                
        if (order.getVisitDate().isBefore(LocalDate.now())) {
            throw new BusinessException("已过期的订单无法取消");
        }
        
        if (!"CREATED".equals(order.getStatus())) {
            throw new BusinessException("该订单状态无法取消");
        }
        
        order.setStatus("CANCELLED");
        orderRepository.save(order);
    }
} 